import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useCounterStore } from "@/stores/counter";
const pinia = useCounterStore();

const httpr = axios.create({
  baseURL: 'http://localhost:5145',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
httpr.interceptors.request.use(
  config => {
    // 从localStorage获取token并添加到请求头
    const token =localStorage.getItem("token");
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    ElMessage.error('请求发送失败');
    return Promise.reject(error);
  }
);

// 响应拦截器
httpr.interceptors.response.use(
  response => {
    // 请求成功
    return response;
  },
  error => {
    if (error.response) {
      const status = error.response.status;
      
      switch (status) {
        case 400:
          ElMessage.error('请求参数错误');
          break;
          
        case 401:
          ElMessage.error('未授权，请重新登录');
          localStorage.removeItem('token');
          router.push('/');
          break;
          
        case 403:
          ElMessage.error('拒绝访问');
          break;
          
        case 404:
          ElMessage.error('请求的资源不存在');
          break;
          
        case 500:
          ElMessage.error('服务器内部错误');
          break;
          
        case 502:
          ElMessage.error('网关错误');
          break;
          
        case 503:
          ElMessage.error('服务不可用');
          break;
          
        case 504:
          ElMessage.error('网关超时');
          break;
          
        default:
          ElMessage.error(`连接错误 ${status}`);
      }
    } else {
      // 处理断网的情况
      if (!window.navigator.onLine) {
        ElMessage.error('网络连接已断开');
      } else {
        ElMessage.error('请求超时或服务器异常');
      }
    }
    return Promise.reject(error);
  }
);

export default httpr;
